package cn.kgc.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    //2.创建DateSource实现类对象(推荐懒汉式)
    private static DataSource ds;

    //1.私有化构造器，不让外界通过新建构造器进行访问
    private JDBCUtils() {}

    //3.给DataSource进行初始化
    static {
        try {
            Properties pro= new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            throw new RuntimeException("DataSource初始化错误");
        }
    }

    //4.提供获取链接对象公共的访问方式
    public static Connection getConnection () throws SQLException {
        if (ds != null) {
            return ds.getConnection();
        }
        throw new RuntimeException("DataSource初始化错误");
    }

    //5.封装对象关闭方法
    public static void close (Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                throw new RuntimeException("Connection连接对象关闭异常");
            }
        }
    }

    //6.封装增删改连接对象的方法
    public static void close (Statement st , Connection con) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                throw new RuntimeException("StatementSQL发送对象关闭异常");
            }
        }

        close(con);
    }

    public static void close (ResultSet rs , Statement st , Connection con) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException("ResultSet结果集对象关闭异常");
            }
        }

        close(st,con);
    }
}
